<?php

/**
 * The included AutoCompletion view helper from ZendX is broken as data is
 * passed in the wrong way. This might be due to the fact that it has not 
 * yet been included in the jquery core yet.
 */
class Pldkp_Form_Element_AutoSelector extends ZendX_JQuery_Form_Element_UiWidget
{
    public $helper = "autoSelector";
    
    protected $table       = null;
    protected $valueColumn = null;
    protected $shownColumn = null;
    
    /**
     * 
     * @param string $table
     * @return Pldkp_Form_Element_AutoSelector
     */
    public function setTable($table)
    {
        $this->table = $table;
        return $this;
    }
    
    /**
     * 
     * @param string $valueColumn
     * @param string $shownColumn
     * @return Pldkp_Form_Element_AutoSelector
     */
    public function setColumns($valueColumn, $shownColumn)
    {
        $this->valueColumn = $valueColumn;
        $this->shownColumn = $shownColumn;
        
        $this->setJQueryParam('valueColumn', $valueColumn);
        $this->setJQueryParam('shownColumn', $shownColumn);
        
        return $this;
    }
    
    /**
     * @param mixed $value
     * @return Pldkp_Form_Element_AutoSelector
     */
    public function setValue($value)
    {
        if ($value && $this->table && $this->valueColumn && $this->shownColumn) {
            
            $table = new $this->table();
            $select = $table->select()->where($this->valueColumn .' = ?', $value);
            $row = $table->fetchRow($select);
            
            if ($row) {
                $shownColumn = $this->shownColumn;
                $shownValue  = $row->$shownColumn;
                $this->setJQueryParam('shownValue', $shownValue);
            }
        }
        
        return parent::setValue($value);
    }
}